//
//  YZBaseAPI.m
//  VET
//
//  Created by Lam BG on 2018/6/26.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZBaseAPI.h"
#import "YZNetworkManager.h"
#import "SVProgressHUD.h"
#import "SVProgressHUD+Message.h"
#import "YZNetworkConfig.h"

@implementation YZBaseAPI

+ (instancetype)api {
    
    id instance = [[self alloc] init];
    
    return instance;
}

- (instancetype)init {
    
    if (self = [super init]) {
    
        self.urlDomain = [YZNetworkConfig getCurrentDomain];
        
        NSString *token = [YZNetworkConfig getCurrentToken];
        if (token.length > 0) {
            [self addHeaderParam:@"vet_token" value:token];
        }
    }
    
    return self;
}

#pragma mark- public function

- (void)addParam:(NSString*)key value:(nullable id)value {
    
    [self.params setObject:value forKey:key];
}

- (void)addParams:(NSDictionary*)values {
    
    [self.params addEntriesFromDictionary:values];
}

- (void)addHeaderParam:(NSString*)key value:(id)value {
    
    [self.headerParams setObject:value forKey:key];
}

- (void)addHeaderParams:(NSDictionary*)values {
    
    [self.headerParams addEntriesFromDictionary:values];
}

#pragma mark- request function

// 发起请求

- (RACSignal*)getRequest {
    
    return [self reqeustWithMethod:GET];
}

- (RACSignal*)postRequest {
    
    return [self reqeustWithMethod:POST];
}

- (RACSignal*)putRequest {
    
    return [self reqeustWithMethod:PUT];
}

- (RACSignal*)patchRequest{
   return [self reqeustWithMethod:PATCH];
}

- (RACSignal*)deleteRequest {
    
    return [self reqeustWithMethod:DELETE];
}

- (RACSignal*)reqeustWithMethod:(YZHTTPMethod)method {
    
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        
        // 是否显示菊花
        [self requestBegin];
        NSString *url = [NSString stringWithFormat:@"%@%@", self.urlDomain, self.action];
        [[[YZNetworkManager sharedInstance] requestURL:url whitParams:self.params withHeaders:self.headerParams  withMethod:method] subscribeNext:^(NSDictionary* data) {
            
            [subscriber sendNext:data];
            
        } error:^(NSError * _Nullable error) {
            
#ifdef DEBUG
            // debug 时 显示错误信息
            [self showErrorInfo:error];
#endif
            [self requestEnd];
            [subscriber sendError:error];
            
        } completed:^{
            
            [self requestEnd];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^(){}];
    }];
}

// 模擬请求
- (RACSignal*)fakeRequest {
    
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        
        // 是否显示菊花
        [self requestBegin];
        int delay = arc4random() % 3;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
//            if (delay % 2 == 0) {
            
                // success 流程
                [self requestEnd];
                [subscriber sendNext:self.fakeData];
//            } else {
//
//                // error 流程
//                NSError *error = [NSError errorWithDomain:@"test" code:100 userInfo:@{NSLocalizedDescriptionKey : @"test error"}];
//                [self showErrorInfo:error];
//                [subscriber sendError:error];
//            }
            
            [subscriber sendCompleted];
        });
        
        return [RACDisposable disposableWithBlock:^(){}];
    }];
}

#pragma mark- private funciton

- (void)requestBegin {
    
    // 是否显示菊花
    if (self.showLoadingStatus) [SVProgressHUD show];
}

- (void)requestEnd {
    
    // 是否隐藏菊花
    if (self.showLoadingStatus) [SVProgressHUD dismiss];
}

- (void)showErrorInfo:(NSError*)error {
    
    // 显示错误信息
    self.showLoadingStatus = NO;
    NSString *errorCode = [@(error.code) stringValue];
    NSString *message = error.userInfo[NSLocalizedDescriptionKey];
    [SVProgressHUD yz_showError:[NSString stringWithFormat:@"%@(%@)", message, errorCode]];
}

#pragma mark - getter 懒加载

- (NSMutableDictionary *)params {
    
    if (_params == nil) {
        
        _params = [NSMutableDictionary dictionary];
    }
    
    return _params;
}

- (NSMutableDictionary *)headerParams {
    
    if (_headerParams == nil) {
        
        _headerParams = [NSMutableDictionary dictionary];
    }
    
    return _headerParams;
}

@end
